package org.jeecg.modules.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.mapper.FlowerTagpreMapper;
import org.jeecg.modules.flower.service.IFlowerLoseInfoService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecg.modules.flower.service.IFlowerTagpreService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 预出库台账
 * @Author: jeecg-boot
 * @Date: 2022-06-24
 * @Version: V1.0
 */
@Service
public class FlowerTagpreServiceImpl extends ServiceImpl<FlowerTagpreMapper, FlowerTagpre> implements IFlowerTagpreService {

    private static final String synTag = "pre19091";

    @Resource
    private IFlowerLoseInfoService flowerLoseInfoService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer flowerLose(FlowerLose flowerLose) throws Exception {
        QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("variety_code", flowerLose.getVarietyCode());
//        String channel,String accountno,
//        queryWrapper.eq("accountno", flowerLose.getacc());
//        queryWrapper.eq("channel", flowerLose.getVarietyCode());


        queryWrapper.eq("packing_specifications", flowerLose.getPackingSpecifications());
        queryWrapper.eq("flower_pole_length", flowerLose.getFlowerPoleLength());
        queryWrapper.eq("storehouse", flowerLose.getStorehouse());
        queryWrapper.eq("state", 1);
        queryWrapper.orderByAsc("stock_in_time");
        Integer loseNum = flowerLose.getLoseNum();
        int dealNum = 0;
        int pageSize = 1000;
        int endPage = loseNum % pageSize > 0 ? (loseNum / pageSize + 1) : loseNum / pageSize;
        for (int pageNo = 1; pageNo <= endPage; pageNo++) {
            if (pageNo * pageSize > loseNum) {
                pageSize = loseNum;
            }

            synchronized (synTag) {
                List<String> preSaleIds = new ArrayList<>();
                Page<FlowerTagpre> page = new Page<>(pageNo, pageSize);
                IPage<FlowerTagpre> pageList = this.page(page, queryWrapper);
                List<FlowerTagpre> flowerTagPres = pageList.getRecords();
                List<FlowerLoseInfo> list = new ArrayList<>();
                for (FlowerTagpre flowerTagpre : flowerTagPres) {
                    FlowerLoseInfo flowerLoseInfo = new FlowerLoseInfo();
                    flowerLoseInfo.setFlowerLoseId(flowerLose.getId());
                    flowerLoseInfo.setTagInId(flowerTagpre.getInId());
                    flowerLoseInfo.setTagPreId(flowerTagpre.getId());
                    list.add(flowerLoseInfo);
                    preSaleIds.add(flowerTagpre.getId());
                }
                flowerLoseInfoService.saveBatch(list);
                this.updateStateToLose(preSaleIds);
                dealNum += flowerTagPres.size();
            }
        }
        return dealNum;
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateStateToLose(List<String> preSaleIds) {
        UpdateWrapper<FlowerTagpre> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state", 3);
        updateWrapper.in("id", preSaleIds);
        this.update(updateWrapper);
    }


    /**
     * 确认扣减预出库库存 ==== 根据预出库单来扣减预出库库存，可货损， 可销售 ===》 根据预出库的单号 来过滤
     *
     * @descriptionauthor 财务确认扣减预出库库存
     * @author gf
     * 2022-12-26 14:14
     * [outOrderPreNo, outOrderInfoID, sourceBase, sourceGreenhouse, channel, accountno, variety, varietyCode, storehouse, packingSpecifications, flowerPoleLength, number, state(出库2，货损3)]
     * @return java.lang.Integer
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public  Integer outTagpre(String outOrderPreNo, String outOrderInfoID,String sourceBase,String sourceGreenhouse,String channel,String accountno,String variety, String varietyCode, String storehouse, String packingSpecifications, String flowerPoleLength, Integer number , Integer state) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        //根据品类variety、varietyCode、规格packingSpecifications、花杆长度flowerPoleLength、等级classes、数量number
        if (number <= 0) {
            throw new RuntimeException(variety+ "(" + varietyCode + ")确认数量为0，请重新填写数量");
        }
        Integer i =0;
        synchronized (synTag) {
            LambdaQueryWrapper<FlowerTagpre> tagpreQuery = new LambdaQueryWrapper<>();
            tagpreQuery.eq(FlowerTagpre::getChannel, channel);
            if(StringUtils.isNotBlank(accountno)){
                tagpreQuery.eq(FlowerTagpre::getAccountno, accountno);
            }
            tagpreQuery.inSql( FlowerTagpre::getOutorderId,"  SELECT info.id FROM  t_flower_outorder_preinfo info,t_flower_outorder_pre main  " +
                    "WHERE info.order_id = main.id and  main.order_no = '"+outOrderPreNo+"'");
            tagpreQuery.eq(FlowerTagpre::getSourceBase, sourceBase);
            tagpreQuery.eq(FlowerTagpre::getSourceGreenhouse, sourceGreenhouse);
            tagpreQuery.eq(FlowerTagpre::getStorehouse, storehouse);
            tagpreQuery.eq(FlowerTagpre::getVarietyCode, varietyCode);
            tagpreQuery.eq(FlowerTagpre::getPackingSpecifications, packingSpecifications);
            tagpreQuery.eq(FlowerTagpre::getFlowerPoleLength, flowerPoleLength);
            //预出库出库时，需要根据业务员来进行扣减。：：业务员销售确认只能确认自己预出库的数据。2022年12月2日16:55:09---在选择预出库单号就控制了2022年12月26日14:10:57只能选择自己的。
//            tagpreQuery.eq(FlowerTagpre::getCreateUser, sysUser.getUsername());
            tagpreQuery.eq(FlowerTagpre::getState, 1);//已入库的台账
            tagpreQuery.orderByAsc(FlowerTagpre::getStockInTime);

            Page<FlowerTagpre> page = new Page<FlowerTagpre>(1, number);
            IPage<FlowerTagpre> tageinfoPage = this.page(page, tagpreQuery);
            List<FlowerTagpre> taginfoRecords = tageinfoPage.getRecords();
            if (taginfoRecords.size() < number) {
                log.error(variety+ varietyCode+ channel+"（" + storehouse +"-" +  packingSpecifications + "-" + flowerPoleLength + "）" + "预出库库存（"+taginfoRecords.size()+"）不足" + number + "，请修改数量！outOrderInfoID："+outOrderInfoID);
                throw new RuntimeException(variety+ varietyCode + channel+"（"+ storehouse  + "-" + packingSpecifications + "-" + flowerPoleLength + "）" + "预出库库存（"+taginfoRecords.size()+"）不足" + number + "（预出库库存数量" + taginfoRecords.size() + "），请修改数量！outOrderInfoID："+outOrderInfoID);
            }
            List<FlowerTagpre> list = new ArrayList<>();
            List<String> tagpreIds = new ArrayList<>();
            for (FlowerTagpre flowerTagpre : taginfoRecords) {
                tagpreIds.add(flowerTagpre.getId());
                i++;
            }
            if(tagpreIds.size()>0){
                UpdateWrapper<FlowerTagpre> updateWrapper =new UpdateWrapper<>();
                updateWrapper.set("state",state);
                updateWrapper.set("pre_sure_id", outOrderInfoID);
                updateWrapper.in("id", tagpreIds);
                this.update(updateWrapper);//保存预出库台账
            }
        }
        return i;
    }
}
